<template>
  <div class="apply_page">
    <van-nav-bar
      title="事项办理申请"
      left-arrow
      @click-left="$router.go(-1)"
      fixed
    />
    <div class="base_info">
      <p>申请人信息</p>
      <van-field
        v-model="form.username"
        label="姓名"
        placeholder="请输入姓名"
        clearable
        class="repair_input_box"
        required
      />
      <van-field
        v-model="form.idcardNo"
        label="身份证号"
        placeholder="请输入身份证号"
        clearable
        class="repair_input_box"
        required
      />
      <van-field
        v-model="form.contactPhone"
        type="number"
        label="手机号"
        placeholder="请输入手机号"
        clearable
        maxlength="15"
        class="repair_input_box"
        required
      />
    </div>
    <div class="devide_div"></div>
    <div class="base_info">
      <p>所需材料</p>
      <div class="image_box" v-for="item in items" :key="item.id">
        <div class="content_desc">
          {{ item.attachName }}<br />
          <span @click="downloadFile(item)" class="download_btn">下载</span>
        </div>
        <van-uploader
          v-model="item.avatar"
          :max-count="5"
          :name="item.attachName"
          class="img_upload_box"
          :before-read="beforeRead"
          :before-delete="beforeDelete"
          :after-read="afterRead"
        />
      </div>
    </div>
    <div class="devide_div"></div>
    <div class="base_info">
      <p>收件方式</p>
      <van-radio-group v-model="form.receiveType" class="radio_group_box">
        <van-radio icon-size="24px" name="1" checked-color="#DC4630"
          ><span
            :style="{ color: form.receiveType == '1' ? '#333333' : '#999999' }"
            >自取</span
          ></van-radio
        >
        <van-radio
          icon-size="24px"
          name="2"
          checked-color="#DC4630"
          style="margin-top:30px"
          ><span
            :style="{ color: form.receiveType == '2' ? '#333333' : '#999999' }"
            >EMS邮政（快递费为到付）</span
          ></van-radio
        >
      </van-radio-group>
      <van-field
        v-if="form.receiveType == '2'"
        v-model="form.address"
        label="收件地址"
        placeholder="请输入收件地址"
        clearable
        class="repair_input_box"
        required
      />
    </div>
    <van-button
      :disabled="!disabled"
      class="next_btn apply_btn"
      @click="contact()"
      >申 请</van-button
    >
    <van-popup v-model="showLoading">
      <van-loading color="#DC4630" />
    </van-popup>
    <van-popup v-model="progress" style="width:80%;padding:10px 0;">
      <van-progress :percentage="percent" />
    </van-popup>
  </div>
</template>

<script>
import api from "@/controller/govService.js";
import constant from "@/controller/constant.js";
import { notEmpty } from "../../../emptyTest";
import uploadService from "@/controller/mine.js";
import util from "@/controller/Common/util.js";
import { Dialog } from "vant";
export default {
  data() {
    return {
      form: {
        username: "",
        idcardNo: "",
        contactPhone: "",
        applyInfos: [],
        receiveType: "1",
        address: ''
      },
      showLoading: false,
      items: [],
      percent: 0,
      progress: false
    };
  },
  computed: {
    disabled: function() {
      return (
        notEmpty(this.form.username) &&
        notEmpty(this.form.idcardNo) &&
        notEmpty(this.form.contactPhone)
      );
    }
  },
  mounted() {
    this.items = this.$route.query.serviceAttaches;
  },
  methods: {
    contact() {
      if (!util.validatePhoneNum(this.form.contactPhone)) {
        this.$toast("请输入合法手机号");
        return;
      }
      if (!util.validateIdCardNumber(this.form.idcardNo)) {
        this.$toast("请输入合法身份证号");
        return;
      }
      if (this.form.receiveType === '2') {
        if (!notEmpty(this.form.address)) {
          this.$toast("请输入地址");
          return;
        }
      }
      this.showLoading = true;
      this.form.applyInfos = [];
      this.items.forEach(e => {
        this.form.applyInfos.push({
          attachName: e.attachName,
          attachUrl: e.imgList.toString()
        });
      });
      const data = {
        username: this.form.username,
        idcardNo: this.form.idcardNo,
        contactPhone: this.form.contactPhone,
        serviceId: this.$route.query.id,
        receiveType: Number(this.form.receiveType),
        applyInfos: this.form.applyInfos,
        receiveAddress: this.form.receiveType === '2'?this.form.address:''
      };
      api
        .service_v1_apply(data)
        .then(res => {
          if (res.code === "0") {
            this.$toast("申请成功");
            this.$router.go(-4)
          } else {
            if (res && res.msg) {
              this.$toast(res.msg);
            } else {
              this.$toast(constant.unusualMsg);
            }
          }
        })
        .catch(() => {})
        .then(() => {
          this.showLoading = false;
        });
    },
    downloadFile(val) {
      document.addEventListener(
        "deviceready",
        this.downloadFun(val).bind(this),
        false
      );
    },
    downloadFun(val) {
      let _this = this;
      window.requestFileSystem(
        // eslint-disable-next-line no-undef
        LocalFileSystem.PERSISTENT,
        0,
        function(fs) {
          fs.root.getFile(
            val.fileName,
            { create: true, exclusive: false },
            function(fileEntry) {
              _this.downLoadImg(fileEntry, val);
            },
            function() {}
          );
        },
        function() {}
      );
    },

    downLoadImg(fileEntry, val) {
      // 初始化FileTransfer对象
      let _this = this;
      // eslint-disable-next-line no-undef
      let fileTransfer = new FileTransfer();
      // 服务器下载地址
      let uri = encodeURI(val.attachUrl);
      // 调用download方法
      fileTransfer.download(
        uri, //uri网络下载路径
        fileEntry.nativeURL, //url本地存储路径
        function() {
          // _this.$toast("文件下载完成");
          // fileEntry.file(() => {
          //   Dialog.confirm({
          //     title: "提示",
          //     message: `是否打开文件？`
          //   })
          //     .then(() => {
          //       _this.previewFile(fileEntry);
          //     })
          //     .catch(() => {});
          // })
          _this.progress = false;
          Dialog({
            message: `请在手机 文件管理APP/内部存储 的根目录下查找下载的名为"${val.fileName}"的文件`
          });
        },
        function() {
          Dialog({ message: "文件下载失败，请稍后再试" });
        }
      );
      fileTransfer.onprogress = function(progressEvent) {
        _this.progress = true;
        _this.percent = 0;
        _this.percent = (
          (progressEvent.loaded / progressEvent.total) *
          100
        ).toFixed(1);
        if (_this.percent === 100 || _this.percent > 100) {
          _this.progress = false;
        }
      };
    },
    // previewFile(fileEntry) {
    //   // let _this = this
    //   // 调用cordova-plugin-file-opener2插件实现用第三方app打开文件
    //   cordova.plugins.fileOpener2.showOpenWithDialog(
    //     // 此处必须填写cdvfile://地址，不然android7.0+会报文件权限错误
    //     fileEntry.nativeURL.toInternalURL(), //文件本地地址转cdvfile://地址
    //     // fileTypeArr[_this.fileType], //文件类型，这里我是写了一个mime-Type类型合集fileTypeArr来调用
    //     function onSuccess() {},
    //     function onError() {
    //       Dialog({ message: `出错！请在${cordova.file.externalDataDirectory}目录下查看`});
    //     }
    //   );
    // },
    beforeDelete(file) {
      const lastModifyTime = file.file.lastModified;
      let arr = this.items;
      let deleteIndex = null;
      for (let i = 0; i < arr.length; i++) {
        const e = arr[i];
        if (e.avatar) {
          for (let j = 0; j < e.avatar.length; j++) {
            const ele = e.avatar[j];
            if (lastModifyTime == ele.file.lastModified) {
              deleteIndex = j;
            }
          }
        }
      }
      this.$nextTick(() => {
        for (let index = 0; index < arr.length; index++) {
          let element = arr[index];
          if (deleteIndex || deleteIndex === 0) {
            if (element.imgList) {
              element.imgList.splice(deleteIndex, 1);
            }
          }
        }
      });
      return true;
    },
    beforeRead(file) {
      const acceptImgs = ["image/jpeg", "image/png", "image/jpg"];
      if (!acceptImgs.includes(file.type)) {
        this.$toast("请上传JPG或者PNG格式的图片!");
        return false;
      }
      this.showLoading = true;
      return true;
    },
    afterRead(file, detail) {
      let formData = new FormData();
      formData.append("file", file.file);
      let i = this.items.findIndex(e => e.attachName === detail.name);
      uploadService
        .upload_image(formData)
        .then(res => {
          if (res.data.code === "0") {
            this.$toast("图片上传成功！");
            if (this.items[i].imgList) {
              this.items[i].imgList.push(res.data.datas);
            } else {
              this.items[i].imgList = [];
              this.items[i].imgList.push(res.data.datas);
            }
          } else {
            if (res && res.data && res.data.msg) {
              this.$toast(res.data.msg);
            } else {
              this.$toast(constant.unusualMsg);
            }
          }
        })
        .catch(() => {})
        .then(() => {
          this.showLoading = false;
          return true;
        });
    }
  }
};
</script>

<style lang="scss" scoped>
@import "../../../styles/workstation.scss";

.apply_page {
  background: #ffffff;
  height: 100%;
  position: relative;

  .base_info {
    p {
      font-size: 18px;
      color: #333333;
      line-height: 25px;
      padding: 10px 15px;
      border-bottom: 1px solid rgba(226, 226, 226, 0.5);
    }

    .radio_group_box {
      padding: 15px;
      border-bottom: 1px solid rgba(226, 226, 226, 0.5);
    }
  }

  .image_box {
    padding: 10px 15px 0;
    border-bottom: 1px solid rgba(226, 226, 226, 0.5);

    .content_desc {
      line-height: 20px;
      font-size: 14px;
      color: #333333;
      width: 245px;
      word-break: break-all;
      float: left;

      .download_btn {
        background: rgba(220, 70, 48, 0.1);
        border-radius: 2px;
        font-size: 10px;
        color: #dc4630;
        text-align: center;
        line-height: 14px;
        padding: 2px 8.5px;
      }
    }

    .img_upload_box {
      float: right;
    }
  }

  .image_box::after {
    content: "\20";
    display: block;
    height: 0;
    clear: both;
  }

  .image_box::before {
    position: absolute;
    left: 0.21333rem;
    color: #f44;
    font-size: 0.37333rem;
    content: "*";
  }

  .van-popup {
    background-color: #ffffff00;
  }
}
</style>

<style lang="scss">
.apply_page {
  .van-field__control {
    text-align: right;
    font-size: 14px;
  }

  .repair_input_box {
    .van-field__control {
      margin-right: 24px;
    }
  }

  .image_box {
    .van-uploader__preview-image {
      width: 80px;
      height: 65px;

      .van-image__error,
      .van-image__img,
      .van-image__loading {
        border-radius: 5px;
      }
    }

    .van-uploader__upload {
      width: 80px;
      height: 65px;
      border-radius: 5px;
      border-style: solid;
      background-color: #f5f7fa;
    }

    .van-uploader__upload-icon {
      font-size: 25px;
    }
  }
}
</style>
